package com.mzy.javaapi.IO.JSONIO;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

import java.io.*;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author mzy
 * @Date 2022/8/12 14:07
 * @Version 1.0
 */

/**
 * JSON深层对象读取修改
 */
public class Demo {
    public static void main(String[] args) throws IOException {
        // Json转对象
        String finalPath1 = "F:\\每日脚本暂存\\新建文件路径\\2022.08.12\\dnodeEps.json";
//        Person person1 = JsonUtils.jsonFile2Object(finalPath1, Person.class);
//        System.out.println(person1.toString());


        // 读对应的json
        String string = JsonUtils.readStringFromFile(finalPath1, "utf-8");

        JSONObject excelArray = JSON.parseObject(string);
        JSONArray jsonArray = excelArray.getJSONArray("dnodeInfos");
        for (int i = 0; i < jsonArray.size(); i++) {
            jsonArray.getJSONObject(i).put("dnodeFqdn","127.0.0.1");
//            System.out.println(jsonArray.getJSONObject(i).getString("dnodeFqdn"));
        }
        System.out.println(jsonArray.toString());
        System.out.println(JSONObject.toJSONString(excelArray,true));
        String s = JSONObject.toJSONString(excelArray, true);
        writeContent(s,finalPath1);
    }


    /**
     * 写内容
     *
     * @param content 内容
     * @param filePath 文件路径
     * @return
     */
    public static void writeContent(String content, String filePath) {
        File file = new File(filePath);
        try(
                FileOutputStream fileOutputStream = new FileOutputStream(file, false);
                Writer write = new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8);
        ) {
            // 将内容写入文件
            write.write(content);
            write.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
